#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

char sendbuf[] = "I am Linux";
char recbuf[20];
char parrecbuf[20];

void reverse(char *str1)
{
    if (str1 == NULL)
        return;
    char *p = str1, *q = str1;
    while (*q)
        q++;
    q--;
    while (q > p)
    {
        char t = *p;
        *p++ = *q;
        *q-- = t;
    }
}

int main()
{
    int mypipe[2];
    if (pipe(mypipe) < 0)
    {
        perror("pipe failed");
        exit(1);
    }
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork failed");
        exit(1);
    }

    if (pid == 0)
    {
        read(mypipe[0], recbuf, sizeof(sendbuf));
        printf("Child received: %s\n", recbuf);
        reverse(recbuf);
        write(mypipe[1], recbuf, strlen(recbuf));
        exit(0);
    }
    else
    {
        write(mypipe[1], sendbuf, strlen(sendbuf));
        sleep(1);
        read(mypipe[0], parrecbuf, sizeof(parrecbuf));
        printf("Parent received: %s\n", parrecbuf);
        wait(NULL);
    }
    return 0;
}